var userdb = require('../../db/user.db')
var config = require('../../config')
var emit = require('../../emit')
var async = require('async')

function randompassword(length){
    var str = "";
    arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
   
    for(var i=0; i<length; i++){
      pos = Math.round(Math.random() * (arr.length-1));
      str += arr[pos];
    }
    return str;
}

function onsocket(socket,data){
    async.waterfall([
        (callback) =>{
            userdb.getuser(data.user,(err,info) =>{
                if(err){
                    return callback(err);
                }
                if(info){
                    callback('allready exist');
                }else{
                    callback(null);
                }
            });
        },

        (callback) =>{
            var info = {password:randompassword(12),active:true,desc:data.desc};
            userdb.setuser(data.user,info,(err) =>{
                callback(err);
            });
        },

        (callback) =>{
            userdb.adduser(data.user,(err)=>{
                callback(err);
            });
        }
    ],(err) =>{
        if(err){
            console.log(err);
            emit.send(socket,"newuser", {result:false,info:err});
        }else{
            console.log(true);
            emit.send(socket,"newuser", {result:true});
        }
    });
}

module.exports = {
    onsocket
}